/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.memberView;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.util.Date;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.CardComponentListener;
import com.ruipengkj.bean.TBillDetail;
import com.ruipengkj.bean.TShopCharge;
import com.ruipengkj.bean.TShopRecharge;
import com.ruipengkj.bean.TUser;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.MatcherFormatUtil;
import com.ruipengkj.commons.util.UUID;
import com.ruipengkj.commons.util.jna.QueryMember;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.JPanelBoxLayoutComponent;
import com.ruipengkj.component.RPJButtonBlue;
import com.ruipengkj.component.RPJButtonGray;
import com.ruipengkj.component.RPJButtonWhite;
import com.ruipengkj.component.jdialog.BorderJPanel;
import com.ruipengkj.component.jdialog.IDialog;
import com.ruipengkj.service.TBillDetailService;
import com.ruipengkj.service.TShopChargeService;
import com.ruipengkj.service.TShopRechargeService;
import com.ruipengkj.service.TUserService;
import com.ruipengkj.view.base.BaseDialog;
import com.ruipengkj.view.base.BasePanel;
/**
 * 说明：
 * 会员充值UI
 * @Author：黄盛强
 * @Date：2012-03-20
 */
public class MemberFillCardPanel extends BasePanel implements QueryMember{
	
	private static final long serialVersionUID = 1L;
	
	private JLabelJTextFieldComponent cardNumTF = null;//卡号
	private JLabelJTextFieldComponent telTF = null; //手机号
	private JButton checkButton = null; //查看订单
	
	
	private JLabelJTextFieldComponent nameTF = null;//姓名
	private JLabelJTextFieldComponent moneyTF = null; //余额
	private JLabelJTextFieldComponent fillMoneyTF = null; //充值金额
	private JLabelJTextFieldComponent employeesTF = null; //操作员
	private JLabelJTextFieldComponent rule = null; //赠送金额
	private JButton ruleButton = null;
	
	private JButton sureButton = null; //确定按钮
	private JButton cancelButton = null; //取消
	
//	private JRadioButton cardNumRadio,phoneRadio;

	private TUserService tUserService;//用户操作 
	
	private String userID;//会员编号
	private TBillDetailService tBillDetailService;
	
	private TShopChargeService tShopChargeService;
	private TShopCharge tShopCharge;
	
	private TShopRechargeService  tShopRechargeService;//充值表
	
	public MemberFillCardPanel() {
		tUserService=BuildSpringApplication.getInstance().getTUserServiceImpl();
		tBillDetailService = BuildSpringApplication.getInstance().getTBillDetailServiceImpl();
		tShopChargeService = BuildSpringApplication.getInstance().getTShopChargeServiceImpl();
		tShopRechargeService = BuildSpringApplication.getInstance().getTShopRechargeServiceImpl();
		this.initViews();
		this.initListener();
		cardNumTF.getText().addComponentListener(new CardComponentListener());
	}
	
	private void initViews() {
		JPanel main_jp=uiFactory.createBoxJPanel(BoxLayout.Y_AXIS);
		main_jp.setBorder(BorderFactory.createTitledBorder("会员卡充值"));
		
		cardNumTF = new JLabelJTextFieldComponent(" *", "卡    号：",30);
		telTF = new JLabelJTextFieldComponent("  *", "手 机 号：", 30);
		checkButton = new RPJButtonWhite("查看信息");
		JPanel p1 =uiFactory.createBoxJPanel(BoxLayout.X_AXIS);
		p1.add(cardNumTF);
		p1.add(telTF);
		p1.add(checkButton);
		
		//ApplicationContext.listenCard(cardNumTF.getText(), ApplicationContext.CardType.CT_DLSended);
		ApplicationContext.query_member = this;
		
		nameTF = new JLabelJTextFieldComponent(" *", "姓    名：",30);
		moneyTF = new JLabelJTextFieldComponent(" *", "余    额：", 30);
		fillMoneyTF = new JLabelJTextFieldComponent(" *", "充值金额：", 30);
		
		ruleButton = new RPJButtonWhite("规则管理");
		rule = new JLabelJTextFieldComponent("   赠送金额：", 30, ruleButton);
		rule.getText().setText("无");
		rule.getText().setEditable(false);
		
		employeesTF = new JLabelJTextFieldComponent(" *", "操 作 员：",30);
		employeesTF.getText().setText(ApplicationContext.OPERATOR_NAME);
		employeesTF.getText().setEditable(false);
		sureButton = new RPJButtonBlue("确定(Ctrl+Y)");
		cancelButton = new RPJButtonGray("清空");
		
		nameTF.getText().setEditable(false);
		moneyTF.getText().setEditable(false);
		
		JPanel p3 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		p3.add(sureButton);
		p3.add(cancelButton);
		
		main_jp.add(p1);
		main_jp.add(nameTF);
		main_jp.add(moneyTF);
		main_jp.add(fillMoneyTF);
		main_jp.add(rule);
		main_jp.add(employeesTF);
		main_jp.add(p3);
		this.add(main_jp);
	}
	
	private void initListener(){
		sureButton.addActionListener(this);
		sureButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_Y, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		cancelButton.addActionListener(this);
		checkButton.addActionListener(this);
		telTF.getText().addKeyListener(this);
		ruleButton.addActionListener(this);
		fillMoneyTF.getText().addFocusListener(new myFocusListener());
	}

	
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==sureButton){
			//确定
			String fillMoneyT=fillMoneyTF.getText().getText().trim(); //充值金额
			double giftMoney = 0;
			if(MatcherFormatUtil.MatcherPriceScheme(rule.getText().getText())){
				Double.parseDouble(rule.getText().getText());//赠送金额
			}
			if(!MatcherFormatUtil.MatcherPriceScheme(fillMoneyT)){
				JOptionPane.showMessageDialog(null, "充值金额 不能为空，且小数点左边最多10位数字，右边最多2位数字");
				fillMoneyTF.getText().setText("");
				fillMoneyTF.getText().requestFocus();
				return;
			}
			TUser tUser=new TUser();
			tUser.setMoney(Double.parseDouble(fillMoneyT)+giftMoney);
			if (!rule.getText().getText().equals("无")) {
				tUser.setMoney(tUser.getMoney()+Double.parseDouble(rule.getText().getText()));
			}
			tUser.setPhone(telTF.getText().getText().trim());
			tUser.setCardNum(cardNumTF.getText().getText().trim());
			try {
				if(tUserService.modifyRechargeService(tUser)){
					BuildSpringApplication.getInstance().getTOpLogServiceImpl().addOpLogService("会员充值，卡号为：+"+cardNumTF.getText().getText().trim()+"，充值金额："+fillMoneyT);
					
					TBillDetail tBillDetail = new TBillDetail();//添加明细
					tBillDetail.setDetailID(UUID.GenUUID15());
					tBillDetail.setBillType(ApplicationContext.BILL_BILLTYPE9);
					tBillDetail.setBillID(userID);// 单据编号CHAR(15)
					tBillDetail.setNum(1);
					tBillDetail.setPrice(Double.parseDouble(fillMoneyT));// 价格DECIMAL(20,3)
					tBillDetailService.saveService(tBillDetail);
					//添加资金出入
					ApplicationContext.addMondyInOut(ApplicationContext.MONEYINOUT_TYPE_IN, 
							ApplicationContext.OPERATOR_ID, ApplicationContext.MONEYINOUT_SOURCE_TYPE5, tBillDetail.getDetailID());
					
					TShopRecharge tShopRecharge = new TShopRecharge();
					tShopRecharge.setRechargeID(UUID.GenUUID15());
					tShopRecharge.setWorkShiftID(ApplicationContext.WORKSHIFT_ID);
					tShopRecharge.setHappenTime(new Date());//时间
					tShopRecharge.setMoney(Double.parseDouble(fillMoneyT));//充值金额
					tShopRecharge.setUserID(userID);//充值用户
					if (tShopCharge != null) {
						tShopRecharge.setChargeRuleID(tShopCharge.getChargeID());//充值规则编号
						tShopRecharge.setGiftMoney(giftMoney);//赠送金额
					}
					tShopRechargeService.saveService(tShopRecharge);
					
					JOptionPane.showMessageDialog(null, "充值成功");
				}else{
					JOptionPane.showMessageDialog(null, "充值失败");
				}
				this.setUsetData(null);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}else if(e.getSource()==cancelButton){
			//清空
			this.setUsetData(null);
		}else if(e.getSource()==checkButton){
			//查看信息
			String cardNum=cardNumTF.getText().getText().trim(); //卡号
			String phone=telTF.getText().getText().trim(); //手机号
			try {
				TUser tUser=null;
				if(!cardNum.equals("")){
					if(cardNum.length()>15){
						JOptionPane.showMessageDialog(null, "卡号不能大于15个字");
						return;
					}
					tUser=tUserService.getByCardNumService(cardNum);
				}else if(!phone.equals("")){
					if(phone.length()>11){
						JOptionPane.showMessageDialog(null, "手机号不能大于11个字");
						return;
					}
					tUser=tUserService.getByMobileService(phone);
				} else {
					JOptionPane.showMessageDialog(null, "卡号和手机号不能同时为空");
					return;
				}
				if(tUser==null){
					JOptionPane.showMessageDialog(null, "不存在会员信息");
					return;
				}
				this.setUsetData(tUser);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		} else if (e.getSource() == ruleButton) {
			IDialog baseDialog = new IDialog((JDialog)null, "规则管理", true);
			BorderJPanel mainPanel = new BorderJPanel(new BorderLayout());
			mainPanel.setBackground(Color.white);
			mainPanel.add(new MemberFillCardChargePanel());
			baseDialog.add(mainPanel);
			baseDialog.setSize(1000, 530);
			baseDialog.setLocationRelativeTo(null);
			baseDialog.setResizable(false);
			baseDialog.setVisible(true);
		}
	}
	@Override
	public void keyReleased(KeyEvent e) {
		if(e.getSource()==telTF.getText()){
			//查看订单
			if(e.getKeyCode()==KeyEvent.VK_ENTER){
				checkButton.doClick();
			}
		}
	}

	private void setUsetData(TUser tuser){
		if(tuser!=null){
			userID = tuser.getUserID();
			cardNumTF.getText().setText(tuser.getCardNum());
			telTF.getText().setText(tuser.getMobile());
			nameTF.getText().setText(tuser.getRealName());
			moneyTF.getText().setText(tuser.getMoney()+"");
			fillMoneyTF.getText().setText("");
		}else{
			telTF .getText().setText(""); //手机号
			cardNumTF.getText().setText("");//卡号
			nameTF .getText().setText("");//姓名
			moneyTF.getText().setText(""); //余额
			fillMoneyTF .getText().setText(""); //充值金额
			telTF.getText().requestFocus();
		}
	}
	
	public void showDialog(String detailID) {
		try {
			TBillDetail tBillDetail = tBillDetailService
					.getByIdService(detailID);

			if (tBillDetail != null && tBillDetail.getBillID() != null) {
				TUser tUser = tUserService.getByIdService(tBillDetail
						.getBillID());
				if (tUser != null && tUser.getUserID() != null) {
					telTF.getText().setText(tUser.getMobile());
					cardNumTF.getText().setText(tUser.getCardNum());
					nameTF.getText().setText(tUser.getUserName());
					moneyTF.getText().setText(tUser.getMoney() + ""); // 余额
					fillMoneyTF.getText().setText(tBillDetail.getPrice() + ""); // 充值金额
					
					cardNumTF.getText().setEditable(false);
					fillMoneyTF.getText().setEditable(false);
					
					JPanel boxPanel = new JPanelBoxLayoutComponent(
							new Component[] { telTF, cardNumTF, nameTF,
									moneyTF, fillMoneyTF }, BoxLayout.Y_AXIS);
					BaseDialog baseDialog = new BaseDialog(new JDialog(),
							"会员充值详情", true);
					baseDialog.add(boxPanel);
					baseDialog.setSize(300, 300);
					baseDialog.setResizable(false);
					baseDialog.setLocationRelativeTo(null);
					baseDialog.setVisible(true);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void clear() {
		telTF .getText().setText(""); //手机号
		cardNumTF.getText().setText("");//卡号
		nameTF .getText().setText("");//姓名
		moneyTF.getText().setText(""); //余额
		fillMoneyTF .getText().setText(""); //充值金额
		rule.getText().setText("无");
		telTF.getText().requestFocus();
		ApplicationContext.listenCard(cardNumTF.getText(), ApplicationContext.CardType.CT_DLSended);
		ApplicationContext.query_member = this;
	}

	@Override
	public void queryMember() {
		checkButton.doClick();
	}
	
	class myFocusListener implements FocusListener{

		@Override
		public void focusGained(FocusEvent arg0) {
			//组件获得键盘焦点时调用。
		}

		@Override
		public void focusLost(FocusEvent f) {
			//组件失去键盘焦点时调用。
			TShopCharge tShopCharge = new TShopCharge();
			if(!MatcherFormatUtil.MatcherPriceScheme(fillMoneyTF.getText().getText())){
				return;
			}
			double fillMoney = Double.parseDouble(fillMoneyTF.getText().getText());
			tShopCharge.setAMount(fillMoney);
			try {
				List<TShopCharge> tShopChargeList = tShopChargeService.findService(tShopCharge);
				if (tShopChargeList != null && tShopChargeList.size() != 0) {
					tShopCharge = tShopChargeList.get(0);
					if (tShopCharge.getType().equals("2、放大率xx")) {
						rule.getText().setText(tShopCharge.getGiftAmount()*fillMoney-fillMoney+"");
					} else {
						rule.getText().setText(tShopCharge.getGiftAmount()+"");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
